package cn.cs.controller;

import cn.cs.client.SysDtAreaClient;
import cn.cs.common.*;
import cn.cs.pojo.Agent;
import cn.cs.service.AgentService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping(value = "/agent")
public class AgentController {

    @Resource
    private AgentService agentService;

    @Resource
    private SysDtAreaClient sysDtAreaClient;




    /**
     * 分页查询 经销商档案
     *
     * @param pageNumber
     * @param pageSize
     * @return
     * @throws Exception TODO 添加搜索
     */
    @RequestMapping(value = "/csPlatform/getAgentAllByPage")
    public Dto getAgentAllByPage(Integer pageNumber, Integer pageSize, String area, String name, String person, String phone, String typeId, String parentInvitationCode, String invitationCode, String typesId) throws Exception {
        Map<String, Object> param = new HashMap<>();
        param.put("area", area);
        param.put("name", name);
        param.put("person", person);
        param.put("phone", phone);
        param.put("typeId", typeId);
        param.put("typesId", typesId);
        param.put("invitationCode", invitationCode);
        param.put("parentInvitationCode", parentInvitationCode);
        return DtoUtil.returnSuccess("获取成功", agentService.queryAgentAllPageByMap(param, pageNumber, pageSize));
    }


    /**
     * 分页查询 经销商
     *
     * @param pageNumber
     * @param pageSize
     * @return
     * @throws Exception TODO 添加搜索
     */
    @RequestMapping(value = "/csPlatform/getAgentByPage")
    public Dto getAgentByPage(Integer pageNumber, Integer pageSize, String area, String name, String person, String phone, String typeId, String parentInvitationCode, String invitationCode, String typesId) throws Exception {
        Map<String, Object> param = new HashMap<>();
        param.put("area", area);
        param.put("name", name);
        param.put("person", person);
        param.put("phone", phone);
        param.put("typeId", typeId);
        param.put("typesId", typesId);
        param.put("invitationCode", invitationCode);
        param.put("parentInvitationCode", parentInvitationCode);
        return DtoUtil.returnSuccess("获取成功", agentService.queryAgentPageByMap(param, pageNumber, pageSize));
    }

    /**
     * 新增/编辑 经销商
     * @param agent
     * @return
     */
    @RequestMapping(value = "/csPlatform/updateAgent")
    @Transactional
    public Dto updateAgent(@RequestBody Agent agent)throws Exception {
        String msg = "新增成功";
        if (EmptyUtils.isEmpty(agent.getId())) {
            Map<String, Object> map = agentService.getAgentBYPhone(agent.getPhone());
            if(EmptyUtils.isEmpty(map) || map == null){
                agent.setId(IdWorker.getId());
                agent.setCreateDate(new Date());
                agent.setTypeId("1");
                String code = String.valueOf(agentService.getMaxCode());
                String invitationCode = "";
                if(EmptyUtils.isEmpty(code)){
                    invitationCode = DateUtil.format(new Date(), "yyyyMMdd") + "0001";
                }else{
                    invitationCode = DateUtil.format(new Date(), "yyyyMMdd") + String.format("%04d", Integer.valueOf(code.substring(8, code.length())) + 1);
                }
                agent.setInvitationCode(invitationCode);
                agentService.addAgent(agent);

            }else{
                return DtoUtil.returnFail("操作失败，手机号重复", "001");
            }

        } else {
            msg = "修改成功";
            agent.setModifyDate(new Date());
            agentService.modifyAgent(agent);
        }
        return DtoUtil.returnSuccess(msg);
    }


    /**
     * 删除经销商
     * @param ids
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/csPlatform/delAgent")
    public Dto delAgent(String ids)throws Exception{
        int i = 0;
        for(String id:ids.split(",")){
            i += agentService.deleteAgentById(id);
        }
        if(i>0){
            return DtoUtil.returnSuccess("操作成功", i);
        }else {
            return DtoUtil.returnFail("已有二级经销商，二级经销商不允许删除", "001");
        }
    }

    /**
     * --获取省级区域数据
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/p/getProvinceList")
    public Dto getProvinceList() throws Exception {
        return DtoUtil.returnSuccess("获取成功", agentService.getProvinceList());
    }

    /**
     * --根据省级id获取省会和地级市区域数据
     * @param Pid
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/p/getCityListByPid")
    public Dto getCityListByPid(String Pid) throws Exception {
        return DtoUtil.returnSuccess("获取成功", agentService.getCityListByPid(Pid));
    }

    /**
     * --根据省会id或地级市id获取本市和本市包括的县级市区域
     * -- 选择经销商 排除已选择的
     * @param Pid
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/p/getAreaListByPid")
    public Dto getAreaListByPid(String Pid) throws Exception {
        return DtoUtil.returnSuccess("获取成功", agentService.getAreaListByPid(Pid));
    }

    /**
     * --根据省会id或地级市id获取本市和本市包括的县级市区域
     * @param Pid
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/p/getAreasListByPid")
    public Dto getAreasListByPid(String Pid) throws Exception {
        return DtoUtil.returnSuccess("获取成功", agentService.getAreasListByPid(Pid));
    }

    /**
     * 根据经销商Id查询经销商管辖区域
     * @param agentId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/p/getAgentAreaListById")
    public Dto getAgentAreaList(String agentId) throws Exception {
        return DtoUtil.returnSuccess("获取成功", agentService.getAgentAreaListById(agentId));
    }


    /**
     * 新增 经销商管辖区域
     * @return
     */
    @RequestMapping(value = "/csPlatform/addAgentArea")
    public Dto addAgentArea(String agentId, String areaId)throws Exception{
        String msg = "新增成功";
        Map<String, Object> map = new HashMap<>();
        map.put("id", IdWorker.getId());
        map.put("agent_id", agentId);
        map.put("agent_area", areaId);
        map.put("create_time", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        map.put("agent_level", "1");
        agentService.addAgentArea(map);
        return DtoUtil.returnSuccess(msg);
    }


    /**
     * 删除经销商管辖区域
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/csPlatform/delAgentArea")
    public Dto delAgentArea(String id)throws Exception{
        String arId2 = agentService.getAgentAreaTwoById(id);
        if(EmptyUtils.isEmpty(arId2)){
            int i = agentService.deleteAgentAreaById(id);
            if(i>0){
                return DtoUtil.returnSuccess("操作成功", i);
            }else {
                return DtoUtil.returnFail("操作失败，请刷新后重试", "001");
            }
        }
        return DtoUtil.returnFail("操作失败，对应区域已经有市县经理无法删除", "001");
    }


    /**
     * 根据经销商Id 获取经销商邀请维修师傅人数，附近门店数    A级邀请B级经销商数
     * @param id
     * @param type
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/p/getNumberByAgentId")
    public Dto getNumberByAgentId(String id, String type, HttpServletResponse response)throws Exception{
        response.setHeader("Access-Control-Allow-Origin", "*");
        Agent agent = agentService.getAgentById(id);
        Map<String, Object> map = new HashMap<>();
        if(EmptyUtils.isNotEmpty(agent)){
            String invitationCode = agent.getInvitationCode();
            map.put("invitationCode", invitationCode);
            if("1".equals(type)){
                Long agentNumber = agentService.getAgentNumberByAgentCode(invitationCode);
                map.put("agentNumber", agentNumber);
                return DtoUtil.returnSuccess("查询成功", map);
            }else{
                Long userNumber = agentService.getUserNumberByAgentCode(invitationCode);
                Long shopNumber = agentService.getShopNumberByAgentCode(invitationCode);
                Long agentNumber = agentService.getAgentNumberByAgentCode(invitationCode);

                map.put("userNumber", userNumber);
                map.put("shopNumber", shopNumber);
                map.put("agentNumber", agentNumber);

                return DtoUtil.returnSuccess("查询成功", map);
            }
        }
        return DtoUtil.returnFail("查询失败，经销商Id不存在", "001");
    }


    /**
     * 根据经销商Id查询经销商管辖区域 分级
     * @param agentId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/p/getNextAreaList")
    public Dto getNextAreaList(String agentId, String pId, String type) throws Exception {
        return DtoUtil.returnSuccess("获取成功", agentService.getNextAreaList(agentId, pId, type));
    }

    /**
     * 设置经销商管理员
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/csPlatform/setAgentByAdmin")
    public Dto setAgentByAdmin(String id) throws Exception {
        return agentService.setAgentByAdmin(id);
    }




}
